import React, { useState, useMemo, useEffect } from 'react';
import { for_obj, d_sort, show_mt, useHigh, GridTable, filter_row, useCmd, MainView, Title, obj_int, obj_str, Ret, PanelFind, is_empty, loc } from 'sui';

const Census = ({ hreturn, data, title, col }) => {
    const [main, setMain] = useState();
    const [high] = useHigh(140, 100);
    const umd = useCmd();

    useEffect(() => {
        if (is_empty(data)) {
            return;
        }

        const ret = {};

        data.forEach(d => {
            const sn = obj_str(d, "std");
            const dnum = obj_int(d, "dnum");
            const bnum = obj_int(d, "bnum");
            const num = obj_int(d, "num");

            if (ret[sn]) {
                ret[sn]["dnum"] += dnum;
                ret[sn]["bnum"] += bnum;
                ret[sn]["num"] += num;
            } else {
                d["dnum"] = dnum;
                d["bnum"] = bnum;
                d["num"] = num;

                ret[sn] = d;
            }
        });

        const tmp = [];

        for_obj(ret, (k, v) => tmp.push(v));

        d_sort(tmp, "std");

        setMain(tmp);
    }, [data]);

    const getRow = useMemo(() => {
        const lst = ["std"];
        return filter_row(main, lst, umd.filter);
    }, [main, umd.filter]);

    const getCol = () => {
        if (is_empty(col)) {
            return null;
        }

        const tmp = [
            {name: loc("l_193"), key: 'index', width: 70},
        ];

        const kc = ["std", "num", "dnum", "bnum"];
        const set = new Set();
        kc.forEach(d => set.add(d));

        col.forEach(d => {
            if (set.has(d.sn) ) {
                show_mt(tmp, d, 150);
            }
        })

        return tmp;
    };

    const Left = () => <Title mod={title} sub={loc("l_115")}/>;

    return (
        <MainView>
            <PanelFind left={<Left/>} right={<Ret hcmd={hreturn}/>} hcmd={v => umd.setFilter(v)}/>
            <GridTable col={getCol()} row={getRow} high={high} gref={umd.gref}/>
        </MainView>
    );
};

export {Census};
